import logging
from odoo import models, SUPERUSER_ID
from odoo.exceptions import UserError

_logger = logging.getLogger(__name__)


class MailMessage(models.Model):
    _inherit = 'mail.message'

    def post_message_to_group_user(self, group, message):
        user_types_category = self.env.ref(group, raise_if_not_found=False)
        if not user_types_category:
            raise UserError('Permission group not found！')
        self.post_message_to_users(user_types_category.users, message)

    def post_message_to_users(self, users, message):
        """
        机器人向用户发送消息
        """
        odoobot_id = self.env['res.users'].sudo().browse(SUPERUSER_ID)
        channel_obj = self.env['discuss.channel']
        odoobot = self.env['ir.model.data']._xmlid_to_res_id("base.partner_root")
        for user in users:
            channel_odoo_bot_users = '%s, %s' % (odoobot_id.partner_id.name, user.partner_id.name)
            channel_id = channel_obj.sudo().search([('name', '=', channel_odoo_bot_users)])
            if not channel_id:
                channel_id = channel_obj.create({
                    'name': channel_odoo_bot_users,
                    'channel_type': 'chat',
                })

            result = channel_id.sudo().message_post(
                body=message, author_id=odoobot, message_type="comment", subtype_xmlid="mail.mt_comment")
